package com.gnerv.oauth.controller;

import com.gnerv.oauth.entity.Result;
import com.gnerv.oauth.mapper.UserMapper;
import com.gnerv.oauth.utils.SecurityUtils;
import com.gnerv.oauth.utils.UUIDUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Random;

@CrossOrigin
@Controller
@RequestMapping(value = "/api/oauth")
@SessionAttributes("authorizationRequest")
public class OauthController {

    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    UserMapper userMapper;

    @RequestMapping("/confirm_access")
    @ResponseBody
    public Result getAccessConfirmation(Map<String, Object> model, HttpServletRequest request) throws Exception {
        return Result.response().data("authorization", model);
    }

    @RequestMapping("/phone/code/{phoneNum}")
    @ResponseBody
    public Result getPhoneCode(@PathVariable("phoneNum") String phoneNum) {
        String lower = UUIDUtils.getLower();
        int a = 1000, b = 9999;
        String code = String.valueOf(a + (int) (Math.random() * (b - a + 1)));
        String encode = passwordEncoder.encode(code);
        userMapper.createPhoneUser(lower, phoneNum, encode, phoneNum);
        return Result.response().data("code", code);
    }

    @RequestMapping("/login/user")
    @ResponseBody
    public Result getLoginUser() {
        UserDetails loginUser = SecurityUtils.getLoginUser();
        if(ObjectUtils.isEmpty(loginUser)){
            return Result.response(Result.CODE_401);
        }
        return Result.response().data("user", loginUser);
    }



}
